package com.hmall.order.service.impl;

import com.hmall.common.clients.UserClients;
import com.hmall.common.clients.searchClients;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.OrderService;
import com.hmall.order.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private searchClients searchClients;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;

    @Autowired
    private UserClients userClients;

    @Override
    public Long creatOrder(RequestParams order) {

        Long userId = ThreadLocalUtil.getUserId();


        Item item = searchClients.queryItemByid(order.getItemId());

        long totalFee = item.getPrice() * order.getNum() *100;
        Order order1 = new Order();
        order1.setTotalFee(totalFee);
        order1.setStatus(1);
        order1.setPaymentType(order.getPaymentType());
        order1.setUserId(userId);
        orderMapper.insert(order1);
        OrderDetail orderDetail = OrderDetail.builder().orderId(order1.getId()).itemId(order.getItemId()).num(order.getNum()).name(item.getName())
                .spec(item.getSpec()).image(item.getImage()).price(item.getPrice()).build();
        orderDetailMapper.insert(orderDetail);

        System.out.println(order1.getId());

        Address addressById = userClients.getAddressById(order.getAddressId());
        OrderLogistics orderLogistics = OrderLogistics.builder().orderId(order1.getId()).contact(addressById.getContact()).mobile(addressById.getMobile())
                .city(addressById.getCity()).town(addressById.getTown()).street(addressById.getStreet()).province(addressById.getProvince()).build();

        orderLogisticsMapper.insert(orderLogistics);

        searchClients.inventory(order.getItemId(),order.getNum());

        return order1.getId();
    }
}
